from flask import Blueprint, request, current_app
from models.models import ChatHistory, db
from utils.helpers import api_response
from openai import OpenAI

chat_bp = Blueprint('chat', __name__)

@chat_bp.route('/history', methods=['GET'])
def get_chat_history():
    """
    获取聊天历史记录
    ---
    tags:
      - 聊天
    parameters:
      - name: user_id
        in: query
        type: integer
        required: true
        description: 用户ID
      - name: limit
        in: query
        type: integer
        required: false
        description: 返回记录数量限制
        default: 50
    responses:
      200:
        description: 获取成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            data:
              type: array
              items:
                type: object
                properties:
                  chat_id:
                    type: integer
                    description: 聊天ID
                  message:
                    type: string
                    description: 用户消息
                  response:
                    type: string
                    description: 系统响应
                  timestamp:
                    type: string
                    description: 时间戳
      400:
        description: 缺少必要参数
      500:
        description: 服务器内部错误
    """
    try:
        user_id = request.args.get('user_id', type=int)
        limit = request.args.get('limit', 50, type=int)
        
        if not user_id:
            return api_response(message="请提供用户ID", code=400, status_code=400)
            
        chats = ChatHistory.query.filter_by(user_id=user_id).order_by(
            ChatHistory.timestamp.desc()
        ).limit(limit).all()
        
        history = [{
            "chat_id": chat.chat_id,
            "message": chat.message,
            "response": chat.response,
            "timestamp": chat.timestamp.isoformat()
        } for chat in chats]
        
        return api_response(data=history)
    except Exception as e:
        return api_response(message=str(e), code=500, status_code=500)

@chat_bp.route('/send', methods=['POST'])
def send_chat_message():
    """
    发送聊天消息
    ---
    tags:
      - 聊天
    parameters:
      - name: body
        in: body
        required: true
        schema:
          type: object
          required:
            - user_id
            - message
          properties:
            user_id:
              type: integer
              description: 用户ID
            message:
              type: string
              description: 消息内容
    responses:
      200:
        description: 消息发送成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            message:
              type: string
              example: "消息发送成功"
            data:
              type: object
              properties:
                chat_id:
                  type: integer
                  description: 聊天记录ID
                response:
                  type: string
                  description: AI响应内容
      400:
        description: 参数错误
      500:
        description: 服务器内部错误
    """
    try:
        data = request.json
        if not data or 'user_id' not in data or 'message' not in data:
            return api_response(message="请提供用户ID和消息内容", code=400, status_code=400)
            
        user_id = data['user_id']
        message = data['message']
        
        # 调用大语言模型API获取响应
        try:
            client = OpenAI(
                api_key="sk-746458575c794f43ba72e1404aba54b8",
                base_url="https://api.deepseek.com"
            )
            
            ai_response = client.chat.completions.create(
                model="deepseek-chat",
                messages=[
                    {"role": "system", "content": "你是一个有帮助的助手"},
                    {"role": "user", "content": message},
                ],
                stream=False
            )
            
            response = ai_response.choices[0].message.content
            
        except ImportError:
            current_app.logger.warning("OpenAI SDK未安装，使用简单回显代替")
            response = f"您发送的消息是: {message}"
            
        except Exception as e:
            current_app.logger.error(f"调用AI API出错: {str(e)}")
            response = f"AI服务暂时不可用，您发送的消息是: {message}"
            
        # 保存聊天记录
        chat = ChatHistory(
            user_id=user_id,
            message=message,
            response=response
        )
        
        db.session.add(chat)
        db.session.commit()
        
        return api_response(
            data={
                "chat_id": chat.chat_id,
                "response": response
            },
            message="消息发送成功"
        )
    except Exception as e:
        db.session.rollback()
        return api_response(message=str(e), code=500, status_code=500) 